/**
 * 
 */
package cnpm02.j2ee.group3.logic.utils;

import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

/**
 * Use to send the information or notification to the specific mail
 * @author BINH
 * @version 1.0
 *
 */
public class MailService {
	private static final String SENDER = "atsm.group3@gmail.com";
	private static final String PASSWD = "tranvanbinh1989";
	private static final String HOST = "smtp.gmail.com";
	private static final int PORT = 25;
	private static final String TITLE = "ATSM - %s";
	
	private Session session; 
	private static MailService instance = null;
	
	private MailService() {
		Properties props = new Properties();
		props.put("mail.smtp.host", HOST);
		props.put("mail.smtp.auth", "true");
		props.put("mail.smtp.starttls.enable", "true");
		props.put("mail.debug", "true");
		session = Session.getInstance(props, new Authenticator() {
			@Override
			protected PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication(SENDER, PASSWD);
			}
		});
	}
	
	
	/**
	 * Get the only instance of the mail service
	 * @return {@link MailService}
	 * */
	public static MailService getService() {
		if(instance == null) {
			return new MailService();
		}
		
		return instance;
	}
	
	/**
	 * Do the action: send email
	 * @param receiverEmail receiver
	 * @param subject email subject
	 * @param messageText email content
	 * @return true if sent successfully, if not return false
	 * */
	public boolean send(String receiverEmail, String subject, String messageText) {
		try {
			
			Message message = createMessage(receiverEmail, subject, messageText);
 
			Transport transport = session.getTransport("smtp");
			transport.connect(HOST, PORT, SENDER, PASSWD);
			Transport.send(message);
 
		} catch (MessagingException e) {
			e.printStackTrace();
			return false;
		}
		
		return true;
	}
	
	private Message createMessage(String receiverEmail, String subject,
			String messageText) throws MessagingException {
		MimeMessage message = new MimeMessage(session);
		message.setText(messageText, "UTF-8");
		message.setSubject(String.format(TITLE, subject), "UTF-8");
		message.setFrom(new InternetAddress(SENDER));
		message.setRecipients(Message.RecipientType.TO,
				InternetAddress.parse(receiverEmail));

		return message;
	}
	
	//Test
	public static void main(String...strings) {
	}
}
